
public class SyncBlockThreadComminication {
	static class DataWrap{
		boolean flag;
		int data;
	}
	
	static class ThreadA extends Thread{
		DataWrap dataWrap;
		
		public ThreadA(DataWrap dataWrap){
			this.dataWrap = dataWrap;
		}
		
		@Override
		public void run() {
			for(int i = 0 ; i < 10; i++) {
				synchronized (dataWrap) {
					if (dataWrap.flag) {
						try {
							dataWrap.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
					
					dataWrap.data++;
					System.out.println(getName() + " " + dataWrap.data);
					dataWrap.flag = true;
					dataWrap.notify();
				}	
			}
		}
	}
	
	static class ThreadB extends Thread{
		DataWrap dataWrap;
		
		public ThreadB(DataWrap dataWrap){
			this.dataWrap = dataWrap;
		}
		
		@Override
		public void run() {
			for (int i = 0; i < 10; i++) {
					synchronized (dataWrap) {
						if (!dataWrap.flag) {
							try {
								dataWrap.wait();
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						}
						
						dataWrap.data++;
						System.out.println(getName() + " " + dataWrap.data);
						dataWrap.flag = false;
						dataWrap.notify();
					}
				}	
			}
			
	}
	public static void main(String[] args) {
		//实现两个线程轮流对数据进行加一操作
		
		DataWrap dataWrap = new DataWrap();
		new ThreadA(dataWrap).start();
		new ThreadB(dataWrap).start();
	}

}
